package com.nagat.http.xml;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.InetSocketAddress;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * @author yasenagat  E-mail: yasenagat@163.com
 * @version 创建时间：2012-4-5 下午2:30:09
 * 类说明
 */
public class XmlServer {

	private int port;
	
	public XmlServer() {
	}
	
	public XmlServer(int port) {
		this.port = port;
	}
	
	public void start(){
		
		try {
			HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
		
			server.createContext("/",new HttpHandler() {
				
				@Override
				public void handle(HttpExchange he) throws IOException {

					try {
						String ip = he.getRemoteAddress().getAddress().getHostAddress();
						
						System.out.println(ip);
						
						InputStream input_stream = he.getRequestBody(); 
						
//						BufferedReader reader = new BufferedReader(new InputStreamReader(input_stream));
//						StringBuilder str_builder = new StringBuilder();
//
//						String line = null;   
//						
//						while ((line = reader.readLine()) != null) 
//						{    
//							str_builder.append(line + "\n");    
//						}    
//						
//						System.out.println("接收："+str_builder);
						
						SAXReader saxReader = new SAXReader();
						
			            Document  document = saxReader.read(new InputStreamReader(input_stream));

			            Element rootElm = document.getRootElement();
			            
			            String username = rootElm.element("username").getText();
			            
			            String password = rootElm.element("password").getText();
			            
			            System.out.println(username);
			            System.out.println(password);
			            
						String ret = "OK";
						he.sendResponseHeaders(200, ret.getBytes("utf-8").length);
						
						OutputStream os = he.getResponseBody();
						
						os.write(ret.getBytes());
						
						os.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			});
			
			server.start();
			
			System.out.println("开始监听"+port+"端口");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		
		new XmlServer(9988).start();
	}
}
